import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:smart_translator/app/modules/videoCall/views/CallParams.dart';
import 'package:tencent_rtc_sdk/trtc_cloud.dart';
import 'package:tencent_rtc_sdk/trtc_cloud_def.dart';
import 'package:tencent_rtc_sdk/trtc_cloud_listener.dart';
import 'package:tencent_rtc_sdk/tx_device_manager.dart';
import 'package:share_plus/share_plus.dart';
import '../../../routes/app_pages.dart';
import '../../../utils/CommonUtil.dart';
import '../../../utils/tips.dart';
import '../../../views/controller/MineViewController.dart';
import '../../../views/views/rt_call_view.dart';
import './utils.dart';
import './service.dart';

class VideoCallingController extends GetxController {
  late TRTCCloud trtcCloud;
  late TXDeviceManager txDeviceManager;
  var srcCode = Get.parameters['srcCode']!;
  var srcLang = Get.parameters['srcLang'].obs;
  var tgtCode = Get.parameters['tgtCode']!;
  var tgtLang = Get.parameters['tgtLang']!.obs;
  var currentSpeaker = ''.obs;

  var scrollController = ScrollController().obs;
  var callType = Get.parameters['callType'];

  var callParams = new CallParams();

  var showInviteText = false.obs; //邀请链接已分享
  var isEnter = false.obs; //被邀请者进入房间
  var isLeave = false.obs; //被邀请者离开房间
  var isAddRobert = false; //是否已拉机器人

  var getStream = false.obs;
  var mainPerson = 'admin'.obs; //当前屏幕是谁的画面

  var textContext = RxList([]);

  var tempStream;

  // 底部相关
  var startTime = DateTime.now().obs;
  var isOpenSpeaker = true.obs;
  var isOpenMic = true.obs;
  var isOpenCamera = true.obs;
  var textSize = 16.obs;

  var calFun;
  var lastTimesTamp =0;

  AudioTranslateService audioTranslateService =AudioTranslateService() ;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    // initTrtc();
  }

  @override
  void onClose() {
    super.onClose();
  }

 void changeFontSize(size){
   textSize.value =int.parse(size);
 }

 void  switchView(){
    print('mainPerson.value${mainPerson.value}');
    if(mainPerson.value =='admin'){
      mainPerson.value = 'user';
      return;
    }
    if(mainPerson.value =='user'){
      mainPerson.value = 'admin';
    }
 }

  // 语言部分
  //  语言部分
  void chooseFromLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION);
    if(languageItem['code'] !=srcCode){
      srcCode = languageItem['code'];
      srcLang.value = languageItem['desc'];
      sendSwitchMsg();
    }
    
  }

  void chooseToLanguages() async {
    final languageItem = await Get.toNamed(Routes.LANGUAGE_OPINION);
    if(languageItem['code'] !=tgtCode){
      tgtCode = languageItem['code'];
      tgtLang.value = languageItem['desc'];
      sendSwitchMsg();
    }
  }

  void exchangeLang(){
    final lastSrcCode = srcCode;
    final lastSrcLang = srcLang.value;
    srcCode = tgtCode;
    srcLang.value = tgtLang.value;
    tgtCode = lastSrcCode;
    tgtLang.value = lastSrcLang!;
    sendSwitchMsg();
    videoUtil.transcription(callParams.appId!, callParams.room!, callParams.peerId!, callParams.userId, srcCode, tgtCode);
  }

  initTrtc() async {
    trtcCloud = await TRTCCloud.sharedInstance();
    txDeviceManager = trtcCloud.getDeviceManager();
   trtcCloud.enableAudioVolumeEvaluation(true,TRTCAudioVolumeEvaluateParams(
       enablePitchCalculation:false, enableSpectrumCalculation:false,enableVadDetection:true,interval: 300));
    var listener = initRtcListener();
    trtcCloud.registerListener(listener);
    audioTranslateService.initSocket(addTranslateText);
    print("init success");
    var auth = await videoUtil.rtcAuth(srcCode,tgtCode,callType == 'voice');
    if (auth != null) {
      callParams.userId = auth['user']; // 当前用户的id
      callParams.appId = auth['appId'];
      callParams.room = auth['room'];
      callParams.key = auth['key'];
      callParams.userSig = auth['userSig'];
      callParams.key = auth['key'];
      callParams.inviteUrl = auth['url'];
      callParams.peerId = auth['peerId']; //被邀请者的id

      print("userModel: ${auth}");
      videoUtil.setShareUrl(auth['url']);
      handleInvite();
      trtcCloud.startLocalAudio(TRTCAudioQuality.speech);
      await enterRoom();
      final result = await videoUtil.shareInvite(callType == 'voice');
      print('inviteresult${result}');
      if (result.status == ShareResultStatus.success) {
        showInviteText.value = true;
      }
    }

  }

  void handleInvite() {
    print('click here');
    getStream.value = true;
  }

  void handleSwitchCamera() {
    if (!callParams.isOpenCamera) return;
    if (callParams.isFrontCamera) {
      txDeviceManager.switchCamera(false);
    } else {
      txDeviceManager.switchCamera(true);
    }
    callParams.isFrontCamera = !callParams.isFrontCamera;
  }

  void handleMuteSpeaker() {
    var isOpen = isOpenSpeaker.value;
    print("handle mutespeak: ${isOpen}");
    trtcCloud.muteAllRemoteAudio(isOpen);
    isOpenSpeaker.value = !isOpen;
  }

  void handleMuteMic() {
    var isOpen = isOpenMic.value;
    print("handle mutemic: ${isOpen}");
    trtcCloud.muteLocalAudio(isOpen);
    isOpenMic.value = !isOpen;
  }

  void handleMuteLocalVideo() {
    var isOpen = isOpenCamera.value;
    if(isOpen){
      trtcCloud.stopLocalPreview();
    }else{
      trtcCloud.startLocalPreview(true, callParams.localViewId!);
    }
    // trtcCloud.muteLocalVideo(TRTCVideoStreamType.big, !isOpen);
    isOpenCamera.value = !isOpen;
  }

  void handleHandOff() {
    // TRTCCloud.destroySharedInstance();
    // // trtcCloud.stopLocalPreview();
    // // trtcCloud.stopAllRemoteView();
    audioTranslateService.sendClose();
    // trtcCloud.exitRoom();
    dismissRoom();
    Get.back();
  }

  enterRoom() async {
    if (callType == 'video') {
      if (!(await Permission.camera.request().isGranted) ||
          !(await Permission.microphone.request().isGranted)) {
        Tips.showToast('请先开启麦克风和照相机权限！');
        return;
      }
    }
    if (callType == 'voice') {
      if (!(await Permission.microphone.request().isGranted)) {
        Tips.showToast('请先开启麦克风权限！');
        return;
      }
    }

    trtcCloud.enterRoom(
      TRTCParams(
        sdkAppId: callParams.appId!,
        userId: callParams.userId!,
        userSig: callParams.userSig!,
        roomId: callParams.room!,
        privateMapKey: callParams.key!,
      ),
      callType == 'video' ? TRTCAppScene.videoCall : TRTCAppScene.audioCall,
    );
  }

  displayLocalVideo(viewId) {
    trtcCloud.setVideoEncoderParam(
      TRTCVideoEncParam(videoResolution: TRTCVideoResolution.res_160_90),
    );
    trtcCloud.startLocalPreview(true, viewId);
    trtcCloud.startLocalAudio(TRTCAudioQuality.speech);
    callParams.isOpenCamera = true;
    callParams.isFrontCamera = true;
    callParams.isOpenMic = true;
    callParams.isOpenSpeaker = true;
  }

  displayRemoteVideo(userId) {
    trtcCloud.startRemoteView(
      userId,
      TRTCVideoStreamType.small,
      callParams.remoteViewId!,
    );
  }

  // 开启语音功能
  startAudio() {
    trtcCloud.startLocalAudio(TRTCAudioQuality.speech);
  }

  initRtcListener() {
    return TRTCCloudListener(
      onError: (errCode, errMsg) {
        print('TRTCerror ${errCode}: ${errMsg}');
      },
      onEnterRoom: (result) {
        print('Listenerenter room: ${result}');
      },
      onExitRoom: (reason) {},
      onRemoteUserEnterRoom: (userId) {
        print('Listenerremote: ${userId}');
        print('callParams.peerId${callParams.peerId}');
        if(userId.toString().trim() ==(callParams.peerId.toString().trim())){
          print('ismatch');
          isEnter.value = true;
          startTime.value = DateTime.now();
          isLeave.value = false;
          if(!isAddRobert){
           final transRes= videoUtil.transcription(
                callParams.appId!,
                callParams.room!,
                callParams.peerId!,
                callParams.userId,
              srcCode,
              tgtCode,
            );
           print('transRes${transRes}');
           isAddRobert = true;
           // if(transRes ==true){
           //   isAddRobert = true;
           // }
          }
          Future.delayed(Duration(seconds: 2), () {
            sendSwitchMsg();
          });
          Future.delayed(Duration(seconds: 3), () {
            sendAvatarUrl();
          });
          Future.delayed(Duration(seconds: 3), () {
            sendAdminName();
          });

          displayRemoteVideo(userId);
        }
      },
      onRemoteUserLeaveRoom: (String userId,userInfo) {
        if(userId.toString().trim() ==(callParams.peerId.toString().trim())){
          print('he is leave');
          isLeave.value = true;
          handleHandOff();
        }
      },
      onUserAudioAvailable: (userId, available) {
        print('Listeneraudio available: ${userId}');
      },
      onUserVideoAvailable: (userId, available) {
        print('Listenervideo available: ${userId}');
      },
      onRecvCustomCmdMsg: (userId, cmdId, seq, message) {
        Map<String, dynamic> jsonMap = jsonDecode(message);
        if(cmdId ==123){
          print('switchmnsg');
        }
        print('jsonMap${jsonMap}');
        // if (jsonMap['sender'] == callParams.userId){
        //   print('checkspeak');
        //   currentSpeaker.value = 'left';
        //   print('currentSpeaker.value${currentSpeaker.value}');
        //   Future.delayed(Duration(milliseconds: 100), () {
        //     currentSpeaker.value = '';
        //   });
        // }
        //
        // if ((jsonMap['sender'].toString() == (callParams.peerId).toString())){
        //   currentSpeaker.value = 'right';
        //   Future.delayed(Duration(milliseconds: 100), () {
        //     currentSpeaker.value = '';
        //   });
        // }
        if (jsonMap['sender'] == callParams.userId &&
            (jsonMap['payload']['end'] == true)) {
          final text = jsonMap['payload']['text'];
          DateTime currentTime = new DateTime.now();
          final sessionId = currentTime.millisecondsSinceEpoch;
          // final sessionId = jsonMap['payload']['roundid'];
          var socketData = {
            "srcLang": srcCode,
            "tgtLang": tgtCode,
            "text": [text],
            "sessionId": sessionId,
            "action": "translate"
          };
          // DateTime currentTime = new DateTime.now();
          int differenceInMillis =currentTime.millisecondsSinceEpoch -lastTimesTamp;
          lastTimesTamp = currentTime.millisecondsSinceEpoch;
          audioTranslateService.sendData(jsonEncode(socketData));
          final textItem = {
            "srcText": text,
            "side":'right',
            "tgtText":'',
            "sessionId": sessionId,
            "currentTime":new DateTime.now(),
            "showTime":differenceInMillis > 60000
          };
          textContext.add(textItem);
          Future.delayed(Duration(milliseconds: 500), () {
            scrollController.value.jumpTo(scrollController.value.position.maxScrollExtent);
          });
          return;
        }
        print('jsonMapsend${jsonMap['sender'].toString()}');
        print('callParams.peerId${callParams.peerId}');

        if ((jsonMap['sender'].toString() == (callParams.peerId).toString()) &&
            (jsonMap['payload']['end'] == true)) {
          final text = jsonMap['payload']['text'];
          DateTime currentTime = new DateTime.now();
          final sessionId = currentTime.millisecondsSinceEpoch;
          print('checktext${text}');
          var socketData = {
            "srcLang": tgtCode,
            "tgtLang": srcCode,
            "text": [text],
            "sessionId": sessionId,
            "action": "translate"
          };
          // DateTime currentTime = new DateTime.now();
          int differenceInMillis =currentTime.millisecondsSinceEpoch -lastTimesTamp;
          lastTimesTamp = currentTime.millisecondsSinceEpoch;
          audioTranslateService.sendData(jsonEncode(socketData));
          final textItem = {
            "srcText": text,
            "side":'left',
            "tgtText":'',
            "sessionId": sessionId,
            "currentTime":new DateTime.now(),
            "showTime":differenceInMillis > 60000,
          };
          textContext.add(textItem);
          Future.delayed(Duration(milliseconds: 500), () {
            scrollController.value.jumpTo(scrollController.value.position.maxScrollExtent);
          });
        }


      },
      onUserVoiceVolume: (List<TRTCVolumeInfo> data,totalVolume){
        for(var i=0;i<data.length;i++){
          var ele =data[i];
          if(ele.volume>20){
            print('checkele1${ele.userId}');
            if(ele.userId ==''){
              print('checkadmin');
            }
            if(ele.userId.toString() ==callParams.peerId.toString()){
              currentSpeaker.value = 'left';
              print('changeright');
            }else{
              currentSpeaker.value = 'right';
              print('changeleft');
            }
          }else{
            currentSpeaker.value = '';
          }
        }
      }
    );
  }

void addTranslateText(receiveData){
    print('checkreceive${receiveData}');
    final receiveId = receiveData['sessionId'].toString();
    final resultText = receiveData['translations'][0];
    print('${resultText}resultText');
    for(var i=0;i<textContext.length;i++){
      if(textContext[i]["sessionId"].toString() ==receiveId){
        textContext[i]["tgtText"] = resultText;
      }
    }
    print('afterfata${textContext}');
    textContext.refresh();
    Future.delayed(Duration(milliseconds: 500), () {
      scrollController.value.jumpTo(scrollController.value.position.maxScrollExtent);
    });
}

void destroy(){
  TRTCCloud.destroySharedInstance();
}

void sendSwitchMsg(){
    int cmdId = 1;
    var testText={
      "action":"switchLang",
      "srcLang": tgtCode,
      "tgtLang": srcCode
    };
    trtcCloud.sendCustomCmdMsg(cmdId,jsonEncode(testText),true,true);
}

void sendAvatarUrl(){
    int cmdId = 2;
    final mineViewController = Get.find<MineViewController>();
    final name = mineViewController.realname.value[0];
    final decodeUrl =  Uri.encodeFull('$name');
    print('decodeUrl${decodeUrl}');
    final urlText={
      "action":"sendAvatarUrl",
      "url":decodeUrl,
    };
    trtcCloud.sendCustomCmdMsg(cmdId,jsonEncode(urlText),true,true);
}
void sendAdminName(){
  int cmdId = 3;
  var sendText={
    "userId":callParams.userId
  };
  trtcCloud.sendCustomCmdMsg(cmdId,jsonEncode(sendText),true,true);
}

// 解散房间
void dismissRoom() async{
  BaseOptions options = BaseOptions();
  options.headers["contentType"] = "application/json";
  options.headers["X-Api-Key"] = '264e03da4958e5ea405dd8f63b87da898757b821';
  print('callParams.room${callParams.room}');
  try{
    Dio dio = new Dio(options);
    var response = await dio.post(
      "https://xy-apis.newtranx.com/chat/v1/room/dismiss?id=${callParams.room}",
    );
    print('check1234${response}');
    if (response.statusCode == 200) {
      print('checkinvite1data${response.data}');
    } else {
      Tips.showToast('${response}');
    }
  } catch(error){
    Tips.showToast('${error}');
  }
}
}
